package com.example.concurrentprogramming8016.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author liyanhao
 * @Date 2023-01-07 17:05
 * 堵塞队列
 */
public class BlockingQueueDemo {
    private static Object Producer;

    public static void main(String[] args) {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(10);
        BlockingQueueDemo blockingQueueDemo = new BlockingQueueDemo();
        BlockingQueueDemo.Producer producer
                = blockingQueueDemo.new Producer(blockingQueue);
        Consumer consumer = blockingQueueDemo.new Consumer(blockingQueue);
        new Thread(() -> {
            producer.run();
        }).start();
        new Thread(() -> {
            consumer.run();
        }).start();
    }


    class Producer implements Runnable {
        private final BlockingQueue<Object> queue;

        public Producer(BlockingQueue queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            int i = 0;
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(3    );
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    System.out.println("生产开始");
                    queue.put(produce());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        }

        public Object produce() {
            return new Data();
        }
    }

    class Consumer implements Runnable {
        private final BlockingQueue<Object> queue;

        public Consumer(BlockingQueue<Object> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    System.out.println("消费开始");
                    consum(queue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        void consum(Object x) {
            System.out.println("消费者消费掉了:" + x);
        }
    }


    class Data {
        public Data() {
            System.out.println("实例化Data");
        }
    }
}
